import 'dart:convert';

import 'package:client/common/config.dart';
import 'package:client/common/fun.dart';
import 'package:client/common/my_http.dart';
import 'package:client/provider/chat_list_provider.dart';
import 'package:client/provider/chat_msg_provider.dart';
import 'package:client/provider/chatroom_member_provider.dart';
import 'package:client/provider/chatroom_msg_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:client/common/conn.dart';
import 'package:client/common/event.dart';
import 'package:client/common/info_route.dart';
import 'package:client/model/user_model.dart';
import 'package:provider/provider.dart';

class AppProvider extends ChangeNotifier {
  static late UserModel _user;
  static late BuildContext _context;
  static late PageController appPage;
  static late Config _config;
  bool isLogin = false;
  bool tcpLinked = false;

  static setUser(UserModel m) {
    _user = m;
    providerInit();
    MyHttp.httpToken(m.token);
    startTcp();
  }

  static UserModel getUser() {
    return _user;
  }

  static init(BuildContext context) {
    _context = context;
    //设置配置项
    _config = Config();

    //心跳
    bus.on(EventBusSet.eventPing, (arg) {
      print("pong");
      Conn.send(InfoRoute.reqPong, "");
    });

    //tcp 连接成功
    bus.on(EventBusSet.tcpLinked, (arg) {
      //上线
      var payload = json.encode({"token": _user.token});
      Conn.send(InfoRoute.reqLogin, payload);
    });

    //tcp 连接断开
    bus.on(EventBusSet.tcpLinkedBreak, (arg) {
      print("tcp break");
      AppProvider app = Provider.of<AppProvider>(_context, listen: false);
      app.tcpLinked = false;
      Conn.close();
      if (app.isLogin) {
        app.isLogin = false;
        app.notifyListeners();
        Fun.dialog("错误", "连接断开");
      }
    });

    //tcp 登录结果
    bus.on(EventBusSet.tcpLogin, (arg) {
      print("tcp login");
      print(arg);

      //修改登录状态
      AppProvider app = Provider.of<AppProvider>(_context, listen: false);
      app.isLogin = true;
      app.tcpLinked = true;
      app.notifyListeners();

      //初始化数据 todo
      // Conn.send(InfoRoute.reqLogin, payload);
    });
  }

  static providerInit() {
    (Provider.of<ChatroomMemberProvider>(_context, listen: false)).init();
    (Provider.of<ChatroomInfoProvider>(_context, listen: false)).init();
    (Provider.of<ChatListProvider>(_context, listen: false)).init();
    (Provider.of<ChatMsgProvider>(_context, listen: false)).init();
  }

  static getConfig() {
    return _config;
  }

  static getContext() {
    return _context;
  }

  static startTcp() {
    AppProvider app = Provider.of<AppProvider>(_context, listen: false);
    if (app.tcpLinked) {
      Fun.dialog("tip", "已连接");
    }
    Conn.start();
  }

  static logOut() {
    AppProvider app = Provider.of<AppProvider>(_context, listen: false);
    app.isLogin = false;
    app.tcpLinked = false;
    Conn.send(InfoRoute.reqLogout, "");
    Conn.close();

    app.notifyListeners();
  }
}
